package com.rectcircle.wechat.entrance;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.rectcircle.wechat.exception.ConfigException;
import com.rectcircle.wechat.msg.vo.Message;
import com.rectcircle.wechat.util.ValidService;
import com.rectcircle.wechat.util.XmlHandler;

/**
 * 
 * 分发器，为了简化开发用户可以直接进入<br>
 * 您的关于消息的业务逻辑只要实现MsgHandler即可，servlet仅需三行
 * 
 * @author RectCircle
 * @version 0.1<br>
 * 2016年7月18日-下午7:56:59<br>
 * Copyright (c) 2016 RectCircle-版权所有<br>
 *
 */
public class Dispatcher {
	
	private String token;
	
	private List<MsgHandler> handlerChain;
	
	public List<MsgHandler> getHandlerChain() {
		return handlerChain;
	}

	public void setHandlerChain(List<MsgHandler> handlerChain) {
		this.handlerChain = handlerChain;
	}

	public Dispatcher(String token) {
		super();
		this.token = token;
		this.handlerChain = new ArrayList<>();
	}

	public Dispatcher() {
		super();
	}
	
	public void distribute(HttpServletRequest request, HttpServletResponse response) throws IOException, ConfigException{
		if(token==null||token.equals("")){
			throw new ConfigException("未配置参数：token");
		}

		request.setCharacterEncoding("UTF-8");
		response.setHeader("content-type","text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		String echostr = request.getParameter("echostr");
		if(echostr!=null){
			String signature = request.getParameter("signature");
			String timestamp = request.getParameter("timestamp");
			String nonce = request.getParameter("nonce");
			if(ValidService.valid(signature, timestamp, nonce, echostr, token)){
				response.getWriter().write(echostr);
			} 
		} else {
			Message receiveMsg = XmlHandler.parseXml(request);
			Message replyMsg = getReplyMsg(receiveMsg);
			if(replyMsg!=null){
				String replyXML = XmlHandler.createXml(replyMsg);
				response.getWriter().write(replyXML);				
			} else {
				response.getWriter().write("");
			}
		}
	}
		
	private Message getReplyMsg(Message receiveMsg){
		Message replyMsg = null;
		for(int i=0; i<handlerChain.size(); i++){
			replyMsg = handlerChain.get(i).handleMsg(receiveMsg);
			if(replyMsg!=null){
				return replyMsg;
			}
		}
		return replyMsg;
	}
	
	public void addHandler(MsgHandler handler){
		handlerChain.add(handler);
	}

	public String getToken() {
		return token;
	}

	public void setToken(String token) {
		this.token = token;
	}

}
